package com.xjz.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xjz.common.enums.ErrorCode;
import com.xjz.constant.CommonConstant;
import com.xjz.exception.BusinessException;
import com.xjz.exception.ThrowUtils;
import com.xjz.mapper.PostFavourMapper;
import com.xjz.mapper.PostThumbMapper;
import com.xjz.model.dto.post.PostEsDTO;
import com.xjz.model.dto.post.PostQueryRequest;
import com.xjz.model.entity.Post;
import com.xjz.model.entity.PostFavour;
import com.xjz.model.entity.PostThumb;
import com.xjz.model.entity.User;
import com.xjz.model.vo.PostVO;
import com.xjz.model.vo.UserVO;
import com.xjz.service.PostService;
import com.xjz.mapper.PostMapper;
import com.xjz.service.UserService;
import com.xjz.utils.SqlUtils;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.sort.SortBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

/**
* @author 86135
* @description 针对表【post(帖子)】的数据库操作Service实现
* @createDate 2025-08-02 15:49:54
*/
@Service
public class PostServiceImpl extends ServiceImpl<PostMapper, Post>
    implements PostService{

    @Resource
    private UserService userService;

    @Resource
    private PostThumbMapper postThumbMapper;

    @Resource
    private PostFavourMapper postFavourMapper;

    @Resource
    private ElasticsearchRestTemplate elasticsearchRestTemplate;


    @Override
    public void validPost(Post post, boolean add) {
        if (post == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        String title = post.getTitle();
        String content = post.getContent();
        String tags = post.getTags();
        if (add ) {
            ThrowUtils.throwIf(StringUtils.isAnyBlank(title, content, tags), ErrorCode.PARAMS_ERROR);
        }

        //有参数则校验
        if (StringUtils.isNotBlank(title) && title.length() > 80) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "标题过长");
        }

        if (StringUtils.isNotBlank(content) && content.length() > 8192) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "内容过长");
        }
    }

    @Override
    public PostVO getPostVO(Post post, HttpServletRequest request) {
        PostVO postVO = PostVO.objToVo(post);
        Long postId = post.getId();

        //1.关联查询用户信息
        Long userId = post.getUserId();
        User user = null;
        if (userId != null && userId > 0) {
            user = userService.getById(userId);
        }

        UserVO userVO = userService.getUserVO(user);
        postVO.setUser(userVO);

        //已登录,获取用户点赞、收藏状态
        User loginUser = userService.getLoginUserPermitNull(request);
        if (loginUser != null) {
            //获取点赞
            QueryWrapper<PostThumb> postThumbQueryWrapper = new QueryWrapper<>();
            postThumbQueryWrapper.eq("postId", postId);
            postThumbQueryWrapper.eq("userId", loginUser.getId());
            PostThumb postThumb = postThumbMapper.selectOne(postThumbQueryWrapper);
            postVO.setHasThumb(postThumb != null);
            //获取收藏
            QueryWrapper<PostFavour> postFavourQueryWrapper = new QueryWrapper<>();
            postFavourQueryWrapper.eq("postId", postId);
            postFavourQueryWrapper.eq("userId", loginUser.getId());
            PostFavour postFavour = postFavourMapper.selectOne(postFavourQueryWrapper);
            postVO.setHasFavour(postFavour != null);
        }

        return postVO;
    }

    /**
     * 获取查询条件
     * @param postQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<Post> getQueryWrapper(PostQueryRequest postQueryRequest) {
        QueryWrapper<Post> queryWrapper = new QueryWrapper<>();
        if (postQueryRequest == null) {
            return queryWrapper;
        }

        String searchText = postQueryRequest.getSearchText();
        String sortField = postQueryRequest.getSortField();
        String sortOrder = postQueryRequest.getSortOrder();
        Long id = postQueryRequest.getId();
        String title = postQueryRequest.getTitle();
        String content = postQueryRequest.getContent();
        List<String> tagList = postQueryRequest.getTags();
        Long userId = postQueryRequest.getUserId();
        Long notId = postQueryRequest.getNotId();

        //拼接查询条件
        if (StringUtils.isNotBlank(searchText)) {
            queryWrapper.and(qw -> qw.like("title", searchText).or().like("content",searchText));
        }

        queryWrapper.like(StringUtils.isNotBlank(title), "title", title);
        queryWrapper.like(StringUtils.isNotBlank(content), "content", content);
        if (CollectionUtil.isNotEmpty(tagList)) {
            for (String tag : tagList) {
                queryWrapper.like("tags","\"" + tag + "\"");
            }
        }

        queryWrapper.ne(notId != null,"id", notId);
        queryWrapper.eq(ObjUtil.isNotNull(id),"id",id);
        queryWrapper.eq(ObjUtil.isNotNull(userId),"userId",userId);
        queryWrapper.orderBy(SqlUtils.validSortField(sortField),sortOrder.equals(CommonConstant.SORT_ORDER_ASC),sortField);
        return queryWrapper;
    }

    /**
     * 分页获取帖子封装
     * @param postPage
     * @param request
     * @return
     */
    @Override
    public Page<PostVO> getPostVOPage(Page<Post> postPage, HttpServletRequest request) {
        List<Post> postList = postPage.getRecords();
        Page<PostVO> postVOPage = new Page<>(postPage.getCurrent(),postPage.getSize(),postPage.getTotal());

        if (CollectionUtil.isEmpty(postList)) {
            return postVOPage;
        }

        //关联查询用户信息
        Set<Long> userIdSet = postList.stream().map(Post::getUserId).collect(Collectors.toSet());
        Map<Long, List<User>> userIdUserListMap = userService.listByIds(userIdSet).stream().collect(Collectors.groupingBy(User::getId));
        //已登录获取用户点赞和收藏状态
        HashMap<Long,Boolean> postIdHasThumbMap = new HashMap<>();
        HashMap<Long, Boolean> postIdHasFavourMap = new HashMap<>();
        User loginUser = userService.getLoginUserPermitNull(request);
        if (loginUser != null) {

            Set<Long> postIdSet = postList.stream().map(Post::getId).collect(Collectors.toSet());
            loginUser = userService.getLoginUser(request);

            //获得点赞
            QueryWrapper<PostThumb> postThumbQueryWrapper = new QueryWrapper<>();
            postThumbQueryWrapper.in("postId", postIdSet);
            postThumbQueryWrapper.eq("userId", loginUser.getId());
            List<PostThumb> postThumbList = postThumbMapper.selectList(postThumbQueryWrapper);
            postThumbList.forEach(postThumb -> postIdHasThumbMap.put(postThumb.getPostId(), true));

            //获取收藏
            QueryWrapper<PostFavour> postFavourQueryWrapper = new QueryWrapper<>();
            postFavourQueryWrapper.in("postId",postIdSet);
            postFavourQueryWrapper.eq("userId",loginUser.getId());
            List<PostFavour> postFavours = postFavourMapper.selectList(postFavourQueryWrapper);
            postFavours.forEach(postFavour -> postIdHasFavourMap.put(postFavour.getPostId(),true));

        }

        //填充信息
        List<PostVO> postVOList = postList.stream().map(post -> {
            PostVO postVO = PostVO.objToVo(post);
            Long userId = post.getUserId();
            if (userIdUserListMap.containsKey(userId)) {
                postVO.setUser(userService.getUserVO(userIdUserListMap.get(userId).get(0)));
            }
            postVO.setHasThumb(postIdHasThumbMap.getOrDefault(post.getId(), false));
            postVO.setHasFavour(postIdHasFavourMap.getOrDefault(post.getId(), false));
            return postVO;
        }).collect(Collectors.toList());

        postVOPage.setRecords(postVOList);

        return postVOPage;

    }

    @Override
    public Page<Post> searchFromEs(PostQueryRequest postQueryRequest) {
        Long id = postQueryRequest.getId();
        Long notId = postQueryRequest.getNotId();
        String searchText = postQueryRequest.getSearchText();
        String title = postQueryRequest.getTitle();
        String content = postQueryRequest.getContent();
        List<String> tags = postQueryRequest.getTags();
        List<String> orTags = postQueryRequest.getOrTags();
        Long userId = postQueryRequest.getUserId();
        //ES 起始页为0
        long current = postQueryRequest.getCurrent() - 1;
        long pageSize = postQueryRequest.getPageSize();
        String sortField = postQueryRequest.getSortField();
        String sortOrder = postQueryRequest.getSortOrder();

        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        //过滤
        boolQueryBuilder.filter(QueryBuilders.termQuery("isDelete",0));
        if (id != null) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("id",id));
        }

        if (notId != null) {
            boolQueryBuilder.mustNot(QueryBuilders.termQuery("id",notId));
        }

        if (userId != null) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("userId",userId));
        }

        if (CollUtil.isNotEmpty(tags)) {
            for (String tag : tags) {
                boolQueryBuilder.filter(QueryBuilders.termsQuery("tags", tag));
            }
        }

        if (CollUtil.isNotEmpty(orTags)) {
            BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
            for (String tag : orTags) {
                queryBuilder.should(QueryBuilders.termQuery("tags", tag));
            }
            queryBuilder.minimumShouldMatch(1);
            boolQueryBuilder.filter(queryBuilder);
        }

        if (StringUtils.isNotBlank(searchText)) {
            boolQueryBuilder.should(QueryBuilders.matchQuery("title",searchText));
            boolQueryBuilder.should(QueryBuilders.matchQuery("description",searchText));
            boolQueryBuilder.should(QueryBuilders.matchQuery("content",searchText));
            boolQueryBuilder.minimumShouldMatch(1);
        }

        if (StringUtils.isNotBlank(title)) {
            boolQueryBuilder.filter(QueryBuilders.matchQuery("title",title));
            boolQueryBuilder.minimumShouldMatch(1);
        }

        if (StringUtils.isNotBlank(content)) {
            boolQueryBuilder.should(QueryBuilders.matchQuery("content",content));
            boolQueryBuilder.minimumShouldMatch(1);
        }

        SortBuilder<?> sortBuilder = SortBuilders.scoreSort();
        if (StringUtils.isNotBlank(sortField)) {
            sortBuilder = SortBuilders.fieldSort(sortField);
            sortBuilder.order(CommonConstant.SORT_ORDER_ASC.equals(sortOrder) ? SortOrder.ASC : SortOrder.DESC);
        }

        //分页
        PageRequest pageRequest = PageRequest.of((int) current, (int) pageSize);
        NativeSearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(boolQueryBuilder).withPageable(pageRequest)
                .withSorts(sortBuilder).build();
        SearchHits<PostEsDTO> searchHits = elasticsearchRestTemplate.search(searchQuery, PostEsDTO.class);
        Page<Post> result = new Page<>();
        result.setTotal(searchHits.getTotalHits());
        List<Post> posts = new ArrayList<>();

        //查出结果后,从数据库中查出最新的动态数据(点赞数、收藏数等)
        if (searchHits.hasSearchHits()) {
            List<SearchHit<PostEsDTO>> searchHitsList = searchHits.getSearchHits();
            List<Long> ids = searchHitsList.stream().map(searchHit -> searchHit.getContent().getId())
                    .collect(Collectors.toList());
            List<Post> postList = listByIds(ids);
            if (CollUtil.isNotEmpty(postList)) {
                Map<Long, List<Post>> idPostMap = postList.stream().collect(Collectors.groupingBy(Post::getId));

                ids.forEach(postId -> {
                    if (idPostMap.containsKey(postId)) {
                        posts.add(idPostMap.get(postId).get(0));
                    } else {
                        //不存在则删除 从es中删除db中物理删除的数据
                        elasticsearchRestTemplate.delete(String.valueOf(postId),PostEsDTO.class);
                    }
                });
            }
        }
        result.setRecords(posts);
        return result;
    }
}




